;; Benchmarks of the non-robust computational geometry functions
;; Copyright (C) 2022  Rocks Mazama
;; 
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; 
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;; 
;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

(ns bench
  (:require
   [criterium.core :as criterium]
   [mazama.compgeom.delaunay.bowyer-watson :refer [delaunay]]))

(defn- read-number [s]
  (clojure.edn/read-string s))

(defn- read-node-line [line]
  (let [[_ x y] (clojure.string/split line #"\s+")]
    (vector (read-number x) (read-number y))))

(defn- ignore? [line]
  (or (empty? line)
      (clojure.string/starts-with? line "#")))

(defn- normalize [file]
  (if (.endsWith file ".gz")
    (-> file
        clojure.java.io/input-stream
        java.util.zip.GZIPInputStream.)
    file))

(defn- read-node-file
  "Read a node file.
  https://www.cs.cmu.edu/~quake/triangle.node.html"
  [file]
  (with-open [rdr (-> file normalize clojure.java.io/reader)]
    (->> (line-seq rdr)
         (map clojure.string/triml)
         (filter (complement ignore?))
         (drop 1)
         (map read-node-line)
         vec)))

(defn- run [file]
  (let [S (read-node-file file)]
    (println (str \newline file "..."))
    (criterium/quick-bench (dorun (delaunay S)))))

(defn -main []
  (let [files ["http://people.eecs.berkeley.edu/~jrs/input/ttimeu10000.node.gz"
               "http://people.eecs.berkeley.edu/~jrs/input/ttimeu100000.node.gz"]]
    (doseq [file files] (run file))))
